package com.chenfan.common.utils;

import com.chenfan.ccp.plug.log.util.TraceIdTaskDecorator;
import com.chenfan.ccp.util.LogUtil;
import com.chenfan.ccp.util.tool.PushUtil;
import com.chenfan.common.extension.util.SmartExecutorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;

import java.util.concurrent.ExecutorService;

/**
 * 钉钉告警工具类
 */
@Slf4j
public class DingTalkAlarm {

    private static ExecutorService executorService = SmartExecutorService.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2);
    {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> executorService.shutdown()));
    }

    /**
     * 发送钉钉告警
     * @param e
     */
    public static void send(Throwable e){
        // 用户端主动关闭 不要告警
        if((e instanceof ClientAbortException)){
            return;
        }
        send("业务异常告警", e.getClass().getSimpleName()+":"+e.getMessage());
    }

    /**
     * 发送钉钉告警
     * @param title
     * @param errorMsg
     */
    public static void send(String title, String errorMsg) {
        LogUtil.AlarmMessage alarmMessage = new LogUtil.AlarmMessage();
        alarmMessage.setTiltle(title);
        alarmMessage.setErrorMsg(errorMsg);
        executorService.execute(new TraceIdTaskDecorator().decorate(() -> {
            try {
                String msg = LogUtil.getServiceMsg(alarmMessage);
                if(log.isDebugEnabled()) {
                    log.debug("准备发送钉钉告警！内容：{}", msg);
                }
                PushUtil.getInstance().send(PushUtil.PushType.DINGDING, "", msg);
            } catch (Exception e) {
                log.error("发送钉钉告警失败！内容：{}", errorMsg, e);
            }
        }));
    }
}
